package ni;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPreceiver extends Thread {

	private final DatagramSocket dataSocket;
	private final P2PNI ni;
	
	private final static int size = 1000;
	private boolean active;
	
	
	public UDPreceiver(DatagramSocket dataSocket, P2PNI ni) {

		this.dataSocket = dataSocket;
		this.ni = ni;
		this.active = true;
	}

	
	public void run() {
        while (isActive()) {
            try {
                DatagramPacket dataPacket = new DatagramPacket(new byte[size], size);
                System.out.println("UDPReceiver : Ready to receive");
                dataSocket.receive(dataPacket);
                System.out.println("UDPReceiver : Packet received : " + dataPacket);
                ni.handlePacketReceived(dataPacket);
            } catch (IOException ex) {
                if (isActive()) {
                    System.out.println("UDPReceiver : Error reading from the input file " + ex.getMessage());
                }
            }
        }
        //dataSocket.close();
        System.out.println("UDPReceiver : closed ");
    }

	public boolean isActive(){
		return active;
	}
	
	public void arret(){
		this.active = false;
	}
	
	public void close_socket_receiver(){
		this.dataSocket.close();
	}
}
